const cloud = require('wx-server-sdk');

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();

const DEFAULT_COLLECTIONS = [
  'users',
  'study_records',
  'match_records',
  'matching_pool',
  'presence',
  'goals'
];

// 小工具：分页删除一个集合的全部文档
async function purgeCollection(colName, dryRun = false) {
  const col = db.collection(colName);
  let totalDeleted = 0;
  let totalCount = 0;

  try {
    // 统计总数（可选）
    const countRes = await col.count();
    totalCount = countRes?.total || 0;
  } catch (e) {
    // 忽略 count 失败，继续
  }

  if (dryRun) {
    return { collection: colName, total: totalCount, deleted: 0, ok: true, dryRun: true };
  }

  try {
    // 分批获取 _id 并删除
    // 每批最多1000
    while (true) {
      const res = await col.field({ _id: true }).limit(1000).get();
      const batch = res?.data || [];
      if (batch.length === 0) break;

      // 逐条删除（CloudBase 不支持一次性 doc 批量）
      for (const doc of batch) {
        try {
          await col.doc(doc._id).remove();
          totalDeleted += 1;
        } catch (e) {
          // 不中断，继续删
          console.warn(`删除失败 ${colName}/${doc._id}:`, e && e.message ? e.message : e);
        }
      }
    }

    return { collection: colName, total: totalCount, deleted: totalDeleted, ok: true, dryRun: false };
  } catch (e) {
    return { collection: colName, total: totalCount, deleted: totalDeleted, ok: false, error: e && e.message ? e.message : String(e) };
  }
}

exports.main = async (event, context) => {
  // 安全确认：必须显式提供确认短语
  const confirm = event && event.confirm;
  if (confirm !== 'DELETE-ALL-DATA') {
    return {
      code: -1,
      message: "危险操作被拒绝：请传入 confirm: 'DELETE-ALL-DATA'",
      hint: "示例: wx.cloud.callFunction({ name: 'clearDatabase', data: { confirm: 'DELETE-ALL-DATA', dryRun: true } })"
    };
  }

  const dryRun = !!(event && event.dryRun); // 仅统计不删除
  const includeCollections = Array.isArray(event && event.collections) && (event.collections.length > 0)
    ? event.collections
    : DEFAULT_COLLECTIONS;

  // 可选的排除列表
  const excludeCollections = Array.isArray(event && event.exclude) ? event.exclude : [];
  const targetCollections = includeCollections.filter(n => !excludeCollections.includes(n));

  const results = [];
  for (const name of targetCollections) {
    const r = await purgeCollection(name, dryRun);
    results.push(r);
  }

  const summary = {
    collections: targetCollections,
    dryRun,
    stats: results,
  };

  const ok = results.every(r => r.ok);

  return {
    code: ok ? 0 : 1,
    message: ok ? (dryRun ? '模拟清理完成（未删除）' : '清理完成') : '部分集合清理失败',
    data: summary
  };
};